﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Xml.Serialization;
using System.Data;
using System.Reflection;
using System.Security.Cryptography;
using System.Web.UI;

namespace WF
{
    public class Helper
    {
        #region ShowMessage & ExceptionHandle
        public static void ShowMessage(System.Web.UI.Page vPage, string vDesc)
        {
            Helper.ShowMessage(vPage, vDesc, false, false);
        }

        public static void ShowMessage(System.Web.UI.Page vPage, string vDesc, bool vCloseWindow, bool vReturnValue)
        {
            string ScriptName = "ErrorDesc";
            string ScriptText = "";

            if (!vPage.ClientScript.IsStartupScriptRegistered(vPage.GetType(), ScriptName))
            {
                vDesc = vDesc.Replace("\n", "");
                vDesc = vDesc.Replace("\r", "");
                vDesc = vDesc.Replace("\"", "'");

                ScriptText = "alert(\"" + vDesc + "\");";

                if (vReturnValue)
                {
                    ScriptText = ScriptText + "\r\n";
                    ScriptText = ScriptText + "window.returnValue = true; ";
                }

                if (vCloseWindow)
                {
                    ScriptText = ScriptText + "\r\n";
                    ScriptText = ScriptText + "window.close();";
                }
                vPage.ClientScript.RegisterStartupScript(vPage.GetType(), ScriptName, ScriptText, true);
            }
        }

        public static void ShowAjaxMessage(System.Web.UI.Page vPage, string vDesc, bool vCloseWindow, bool vReturnValue)
        {
            string ScriptName = "ErrorDesc";
            string ScriptText = "";

            if (!vPage.ClientScript.IsStartupScriptRegistered(vPage.GetType(), ScriptName))
            {
                vDesc = vDesc.Replace("\n", "");
                vDesc = vDesc.Replace("\r", "");
                vDesc = vDesc.Replace("\"", "'");

                ScriptText = "alert(\"" + vDesc + "\");";

                if (vReturnValue)
                {
                    ScriptText = ScriptText + "\r\n";
                    ScriptText = ScriptText + "window.returnValue = true; ";
                }

                if (vCloseWindow)
                {
                    ScriptText = ScriptText + "\r\n";
                    ScriptText = ScriptText + "window.close();";
                }

                vPage.ClientScript.RegisterStartupScript(vPage.GetType(), ScriptName, ScriptText, true);
            }
        }

        public static void ShowAjaxMessage(System.Web.UI.Page vPage, Exception ex, bool vCloseWindow, bool vReturnValue)
        {
            ShowAjaxMessage(vPage, ex.Message, vCloseWindow, vReturnValue);
        }

        public static void ShowOpenWindowMessage(System.Web.UI.Page vPage, string vDesc, bool vCloseWindow, bool vReturnValue, string clientID)
        {
            string ScriptName = "ErrorDesc";
            string ScriptText = "";

            if (!vPage.ClientScript.IsStartupScriptRegistered(vPage.GetType(), ScriptName))
            {
                vDesc = vDesc.Replace("\n", "");
                vDesc = vDesc.Replace("\r", "");
                vDesc = vDesc.Replace("\"", "'");

                ScriptText = "alert(\"" + vDesc + "\");";

                if (vReturnValue)
                {
                    ScriptText = ScriptText + "\r\n";
                    ScriptText = ScriptText + "window.opener.document.all('" + clientID + "').click();";
                }

                if (vCloseWindow)
                {
                    ScriptText = ScriptText + "\r\n";
                    ScriptText = ScriptText + "window.close();";
                }
                vPage.ClientScript.RegisterStartupScript(vPage.GetType(), ScriptName, ScriptText, true);
            }
        }

        public static void ShowModalDialog(System.Web.UI.Page vPage, string url, string feature, string vClickObjectClientID)
        {
            string ScriptName = "ErrorDesc";
            string ScriptText = "";

            if (!vPage.ClientScript.IsStartupScriptRegistered(vPage.GetType(), ScriptName))
            {
                ScriptText = "OpenAction2(\"" + url + "\",\"" + feature + "\",\"" + vClickObjectClientID + "\");";

                vPage.ClientScript.RegisterStartupScript(vPage.GetType(), ScriptName, ScriptText, true);
            }
        }

        public static void OpenPopupWindow(Page vPage, string url, string width, string height)
        {
            string ScriptName = "OpenPopupWindow";
            string ScriptText = "";

            if (!vPage.ClientScript.IsStartupScriptRegistered(vPage.GetType(), ScriptName))
            {
                string feature = "width=" + width + ",height=" + height + ",top=0,left=0,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes";

                ScriptText = "window.open(\"" + url + "\",null,\"" + feature + "\");";

                vPage.ClientScript.RegisterStartupScript(vPage.GetType(), ScriptName, ScriptText, true);
            }
        }

        public static void WindowClose(System.Web.UI.Page vPage, bool vReturnValue)
        {
            string ScriptName = "WindowClose1";
            string ScriptText = "";

            if (!vPage.ClientScript.IsStartupScriptRegistered(vPage.GetType(), ScriptName))
            {
                if (vReturnValue)
                {
                    ScriptText = ScriptText + "\r\n";
                    ScriptText = ScriptText + "window.returnValue = true; ";
                }
                ScriptText = ScriptText + "\r\n";
                ScriptText = ScriptText + "window.close();";

                vPage.ClientScript.RegisterStartupScript(vPage.GetType(), ScriptName, ScriptText, true);
            }
        }

        public static void WindowClose(System.Web.UI.Page vPage, bool vReturnValue, string alertMessage)
        {
            string ScriptName = "WindowClose1";
            string ScriptText = "";

            if (!vPage.ClientScript.IsStartupScriptRegistered(vPage.GetType(), ScriptName))
            {
                ScriptText = ScriptText + "alert('" + alertMessage + "');";
                if (vReturnValue)
                {
                    ScriptText = ScriptText + "\r\n";
                    ScriptText = ScriptText + "window.returnValue = true; ";
                }
                ScriptText = ScriptText + "\r\n";
                ScriptText = ScriptText + "window.close();";

                vPage.ClientScript.RegisterStartupScript(vPage.GetType(), ScriptName, ScriptText, true);
            }
        }

        public static void WindowClose(System.Web.UI.Page vPage, string vReturnValue)
        {
            string ScriptName = "WindowClose1";
            string ScriptText = "";

            if (!vPage.ClientScript.IsStartupScriptRegistered(vPage.GetType(), ScriptName))
            {
                ScriptText = ScriptText + "\r\n";
                ScriptText = ScriptText + "window.returnValue = '" + vReturnValue + "'; ";

                ScriptText = ScriptText + "\r\n";
                ScriptText = ScriptText + "window.close();";

                vPage.ClientScript.RegisterStartupScript(vPage.GetType(), ScriptName, ScriptText, true);
            }
        }
        #endregion

        public static void RefreshLeftFrame(System.Web.UI.Page vPage)
        {
            string ScriptName = "RefreshLeftFrame";
            string ScriptText = "";

            if (!vPage.ClientScript.IsStartupScriptRegistered(vPage.GetType(), ScriptName))
            {
                ScriptText = "parent.leftFrame.__doPostBack('Refresh', '');";
                vPage.ClientScript.RegisterStartupScript(vPage.GetType(), ScriptName, ScriptText, true);
            }
        }

        public static XDocument XmlDocumentToXDocument(XmlDocument xmlDoc)
        {
            if (xmlDoc == null) return null;

            return XDocument.Parse(xmlDoc.OuterXml);
        }

        public static XmlDocument XDocumentToXmlDocument(XDocument xDoc)
        {
            if (xDoc == null) return null;

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xDoc.Root.ToString());

            return xmlDoc;
        }

        public static byte[] StreamToByteArray(Stream stream)
        {
            byte[] ret = new byte[stream.Length];
            stream.Read(ret, 0, (int)stream.Length);

            return ret;
        }

        public static T DeserializeObjectFromXml<T>(XmlDocument doc)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));

            StringReader sReader = new StringReader(doc.InnerXml);
            return (T)xs.Deserialize(sReader);
        }

        public static XmlDocument SerializeObjectToXml<T>(T obj)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            using (MemoryStream stream = new MemoryStream())
            {
                XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
                xs.Serialize(stream, obj);

                stream.Position = 0;
                XmlDocument doc = new XmlDocument();
                doc.Load(stream);

                return doc;
            }
        }

        public static DataTable ListToDataTable<T>(List<T> list)
        {
            if (list == null) return null;

            DataTable dt = new DataTable(typeof(T).ToString() + "_Table");

            PropertyInfo[] pis = typeof(T).GetProperties();
            foreach (PropertyInfo pi in pis)
            {
                DataColumn dc = new DataColumn(pi.Name);
                dt.Columns.Add(dc);
            }


            foreach (T obj in list)
            {
                DataRow row = dt.NewRow();
                foreach (PropertyInfo pi in pis)
                {
                    row[pi.Name] = typeof(T).GetProperty(pi.Name).GetValue(obj, null);
                }

                dt.Rows.Add(row);
            }

            return dt;
        }

        public static DataTable ListToDataTable(List<object> list)
        {
            if (list == null) return null;

            Type t = list[0].GetType();

            DataTable dt = new DataTable(t.ToString() + "_Table");

            PropertyInfo[] pis = t.GetProperties();
            foreach (PropertyInfo pi in pis)
            {
                DataColumn dc = new DataColumn(pi.Name);
                dt.Columns.Add(dc);
            }


            foreach (var obj in list)
            {
                DataRow row = dt.NewRow();
                foreach (PropertyInfo pi in pis)
                {
                    row[pi.Name] = t.GetProperty(pi.Name).GetValue(obj, null);
                }

                dt.Rows.Add(row);
            }

            return dt;
        }

        public static string GenerateMD5Hash(string plainText)
        {
            MD5 md5 = MD5.Create();
            byte[] hashBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(plainText));

            StringBuilder result = new StringBuilder(32);
            foreach (byte b in hashBytes)
            {
                result.Append(b.ToString("x2").ToUpper());
            }

            return result.ToString();
        }

        public static bool PropertiesEqual(object obj1, object obj2)
        {
            if (obj1.GetType() != obj2.GetType()) return false;

            Type t = obj1.GetType();

            PropertyInfo[] pis = t.GetProperties();

            foreach (PropertyInfo pi in pis)
            {
                object v1 = t.GetProperty(pi.Name).GetValue(obj1, null);
                object v2 = t.GetProperty(pi.Name).GetValue(obj2, null);

                var ret1 = v1 != null ? v1.ToString() : null;
                var ret2 = v2 != null ? v2.ToString() : null;

                if (ret1 != ret2) return false;


            }

            return true;
        }

        public static void SaveXmlToFile(XmlDocument doc, string file)
        {
            using (FileStream fs = File.Open(file, FileMode.Create))
            {
                fs.Position = 0;
                XmlWriter xw = XmlWriter.Create(fs);
                doc.WriteTo(xw);
                xw.Flush();
            }
        }

        public static int StringToInt(string inpiut, int defaulrValue)
        {
            try
            {
                return Convert.ToInt32(inpiut);
            }
            catch (Exception ex)
            {
                return defaulrValue;
            }
        }

        public static int StringToInt(string inpiut)
        {
            return StringToInt(inpiut, 0);
        }
    }
}
